package com.syqc.login

import com.syqc.comlib.AppConfigs
import com.syqc.comlib.MenuKey
import com.syqc.comlib.UserConstant
import com.syqc.comlib.entity.AppConfig
import com.syqc.comlib.entity.ToastEntity
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.BuildConfigs
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.Callback
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.LoginEntity
import com.syqc.entity.MenuNo
import com.syqc.monitor.R
import com.syqc.monitor.download.DownLoadUtil
import com.syqc.utils.ChooseCars
import com.syqc.net.Net
import com.syqc.net.ServiceHelper
import com.syqc.utils.AlarmDataUtil
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.UrlUtil
import com.syqc.utils.VideoHostUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.PublishSubject
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import kotlin.concurrent.thread

/** @author joker @date 2022/8/27$ 17:46$ */
object LoginUtil {
    //是否设置报警
    var isSetAlarm = false

    //手机当前经纬度
    var phoneLat = 0.0
    var phoneLng = 0.0

    /** 登录 */
    fun login(
        ip: String,
        port: String,
        userId: String,
        pwdMd5: String,
        callback: ILoginCallback,
        isHttps: Boolean = false
    ) {
        if (!isOkParams(ip, port, userId, pwdMd5, callback)) return
        //清除所有用户数据
        if (isDelete(ip, port, userId)) {
            ChooseCars.clearChooseCar()
            CacheMMKV.clearDefAll()
        }
        UserConstant.isHttps = isHttps
        UserConstant.current_ip = ip
        UserConstant.current_port = port
        Net.changeUrl()
        ServiceHelper.getRepository().changeHost()
        try {
            Thread.sleep(500)
        } catch (_: Exception) {
        }
        NetDataUtil.getColor()
        val ss=ServiceHelper.getRepository().login(
            userId, pwdMd5, Keys.LOGIN_TYPE_USER , "", false, "", phoneLat, phoneLng
        ).subscribe({
            //初始化
            AppConfigs.init()
            UserConstant.current_userId = userId
            UserConstant.loginType = Keys.LOGIN_TYPE_USER
            UserConstant.sessionId = it.sessionId
            UserConstant.videohost = it.videoHost
            UserConstant.videohosts = it.videoHosts
            UserConstant.current_pwd_md5 = pwdMd5
            UserConstant.serviceTime = it.dueDate ?: ""
            thread {
                saveData(ip, port, userId )
                setUserConstant(it)
                downLoadImage(it.logUrl)
                if (it.version.isNullOrEmpty()) {
                    NetDataUtil.getUserSet()
                    UserConstant.platformVersion = UserConstant.PLATFORM_TMN
                    UserConstant.isFeeManager = false
                    UserConstant.isTempPlat = false
                } else {
                    val version = it.version.substring(0, 8).toInt()
                    if (version > 20240625) {
                        UserConstant.platformVersion = version
                        NetDataUtil.isSyncTree = true
                    } else {
                        NetDataUtil.getUserSet()
                        UserConstant.platformVersion = UserConstant.PLATFORM_TMN
                    }
                    //收费新增收费模式兼容
                    if (version >= 20250109) {
                        UserConstant.isFeeManager = true
                    } else {
                        UserConstant.isFeeManager = false
                    }
                    //温度统计兼容
                    if (version >= 20241219) {
                        UserConstant.isTempPlat = true
                    } else {
                        UserConstant.isTempPlat = false
                    }

                }

                AlarmDataUtil.instance.init()
                get808Info()
            }
            thread {
                handMenu(it.menuIds, it.extmenus)
                UserConstant.isHomeData = it.menuIds.contains(MenuKey.MENU_DATA)
                getAppConfig(callback)
            }
        }, {
            callback.onFailure(it.message ?: "")
        })
    }

    /** 是否删除原账号的数据   */
    private fun isDelete(ip: String, port: String, userId: String): Boolean {
        val oldIp = CacheMMKV.decodeStringSave("LOGIN_LAST_IP")
        val oldPort = CacheMMKV.decodeStringSave("LOGIN_LAST_PORT")
        // todo 兼容企业版HTTPS
        if (BuildConfigs.ISHTTPS && oldIp == "www.wdczn.cn" && oldPort == "9999") {
            return false
        }

        return oldIp != ip || oldPort != port || CacheMMKV.decodeStringSave("LOGIN_LAST_USERID") != userId
    }

    /** 保存数据 */
    private fun saveData(
        ip: String, port: String, userId: String,
    ) {
        CacheMMKV.encodeSave(Keys.LOGIN_TYPE_USERID, userId)
        CacheMMKV.encodeSave(Keys.LOGIN_TYPE_IP, ip)
        CacheMMKV.encodeSave(Keys.LOGIN_TYPE_PORT, port)
        // todo 记录账号信息不可删
        CacheMMKV.encodeSave("LOGIN_LAST_USERID", userId)
        CacheMMKV.encodeSave("LOGIN_LAST_IP", ip)
        CacheMMKV.encodeSave("LOGIN_LAST_PORT", port)
        UserConstant.current_ip = ip
        UserConstant.current_port = port
    }

    /** 设置用户相关常量参数 */
    private fun setUserConstant(entity: LoginEntity) {
        UserConstant.current_carId = entity.carId
        UserConstant.current_cmpId = entity.cmpId
        UserConstant.current_car_num = entity.carNum
        UserConstant.current_videos = entity.videos
        UserConstant.adLink_1 = entity.appAdLink1
        UserConstant.adLink_2 = entity.appAdLink2
        UserConstant.adLink_3 = entity.appAdLink3
        AppConfigs.isPlateColorVfy = entity.pwdConvert ?: false
        AppConfigs.isUpPwd = entity.uptPwd ?: false

        VideoHostUtil.handHosts(entity.videoHost, entity.videoHosts)
        CacheMMKV.encode(Keys.CMP_ID, entity.cmpId)

        UserConstant.isRealVideo = entity.menuIds.contains("106")
        UserConstant.isTapeVideo = entity.menuIds.contains("107")

    }

    /** 获取APP自定义设置 */
    private fun getAppConfig(callback: ILoginCallback) {
        ServiceHelper.getRepository().getAppConfig().subscribe({
            AppConfigs.isAlarmFilter = it.alarmFilter
            CacheMMKV.encode(Keys.SETTING_ALARM_SHOW, it.alarmFilter)
            AppConfigs.isAlarms = it.alarms
            AppConfigs.isArrears = it.arrears
            AppConfigs.appGpsColumn = it.appGpsColumn
            AppConfigs.mapMark = it.mapMarker
            AppConfigs.homeSet = it.homeSet
            AppConfigs.isCenter = it.fixCenter ?: false
            AppConfigs.arrearsAuth = if (it.arrearsAuth == null) true else it.arrearsAuth!!
            AppConfigs.quickSet = it.quickSet
            AppConfigs.isOnOffLine = it.onlineNotice ?: false
            val time = it.mapRefreshTime
            if (time == null) {
                AppConfigs.mapRefresh = CacheMMKV.decodeInt(Keys.SETTING_REFRESH_TIME, 5)
            } else {
                AppConfigs.mapRefresh = time.toInt()
            }
            Callback.mapMarkerSub.onNext(true)
            isSetAlarm = it.alarms
            LocationStatusModel.initData()
            callback.onSuccess()
        }, {
            Callback.mapMarkerSub.onNext(false)
            isSetAlarm = CacheMMKV.decodeBoolean(Keys.SETTING_ALARM, false)
            AppConfigs.isAlarms = CacheMMKV.decodeBoolean(Keys.SETTING_ALARM, false)
            AppConfigs.isAlarmFilter = CacheMMKV.decodeBoolean(Keys.SETTING_ALARM_SHOW, false)
            AppConfigs.isArrears = CacheMMKV.decodeBoolean(Keys.SETTING_ARREARS, true)
            AppConfigs.homeSet = CacheMMKV.decodeString(Keys.APP_CFG_HOME_SET, Keys.KEY_HOME_SET)
            AppConfigs.isCenter = CacheMMKV.decodeBooleanSave("isCenter", false)
            AppConfigs.isOnOffLine = CacheMMKV.decodeBooleanSave("isOnOffLine", false)
            AppConfigs.mapRefresh = CacheMMKV.decodeInt(Keys.SETTING_REFRESH_TIME, 5)
            AppConfigs.arrearsAuth = true
            LocationStatusModel.initData()
            callback.onSuccess()
        })
    }


    /** 缓存logo */
    private fun downLoadImage(logUrl: String?) {
        if (logUrl.isNullOrEmpty())
            DownLoadUtil.downloadImage(UrlUtil.getLoginLogoUrl(), "2")
        else {
            DownLoadUtil.downloadImage(UrlUtil.getLoginLogoUrl(logUrl), "2")
        }
        DownLoadUtil.downloadImage(UrlUtil.getLoginBgUrl(), "1")

        DownLoadUtil.downloadImage(UrlUtil.getWelcomeUrl(), "0")
    }

    /**
     * Get808info  808自定义描述
     *
     */
    private fun get808Info() {
        ServiceHelper.getRepository().getSgnList().subscribe({
            LocationStatusModel.initLocations(it)
        }, {})
    }


    private fun isOkParams(
        ip: String,
        port: String,
        userId: String,
        pwdMd5: String,
        callback: ILoginCallback
    ): Boolean {
        if (ip.isEmpty()) {
            callback.onFailure(AppContext.getDescById(R.string.toast_hint_domain_name))
            return false
        }
        if (port.isEmpty()) {
            callback.onFailure(AppContext.getDescById(R.string.hint_toast_platform_port))
            return false
        }
        if (userId.isEmpty()) {
            callback.onFailure(AppContext.getDescById(R.string.hint_toast_user_opt))
            return false
        }
        if (pwdMd5.isEmpty()) {
            callback.onFailure(AppContext.getDescById(R.string.hint_login_pwd))
            return false
        }
        return true
    }

    private fun handMenu(menuIds: MutableList<String>?, extMenus: List<LoginEntity.Extmenu>?) {
        InfoSetModel.isHad(menuIds)
    }
}

